package cn.minsh.lims.eoms.modules.job.task;

import cn.minsh.lims.eoms.modules.app.entity.PlanAgentEntity;
import cn.minsh.lims.eoms.modules.app.entity.PlanRemindEntity;
import cn.minsh.lims.eoms.modules.app.entity.UserInspectionPlanEntity;
import cn.minsh.lims.eoms.modules.app.entity.UserInspectionPlanScopeEntity;
import cn.minsh.lims.eoms.modules.app.enums.BusiTypeEnum;
import cn.minsh.lims.eoms.modules.app.enums.PlanResultEnum;
import cn.minsh.lims.eoms.modules.app.enums.PlanStatusEnum;
import cn.minsh.lims.eoms.modules.app.message.InspectionPlanRemindMsg;
import cn.minsh.lims.eoms.modules.app.service.*;
import cn.minsh.lims.eoms.modules.app.utils.LocalDateUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.minsh.lims.eoms.modules.app.utils.QueueUtils.INSPECTION_ORDER_REMIND;


/**
 * 检查用户的巡检提醒任务
 * 1、未开始工单检查提醒时间
 * @author Administrator
 */
@Component("checkUserInspectionPlanRemindTask")
public class CheckUserInspectionPlanRemindTask implements ITask{

    @Autowired
    private UserInspectionPlanService userInspectionPlanService ;
    @Autowired
    private UserInspectionPlanScopeService userInspectionPlanScopeService ;
    @Autowired
    private PlanRemindService planRemindService ;
    @Autowired
    private QueueSendMessageService queueSendMessageService;
    @Autowired
    private PlanAgentService planAgentService ;


    @Override
    public void run(String params) {

        //读取未开始工单
        List<Integer> statusList = new ArrayList<>() ;
        statusList.add(PlanStatusEnum.NOT_STARTED.getCode()) ;
        statusList.add(PlanStatusEnum.STARTED.getCode()) ;
        QueryWrapper<UserInspectionPlanEntity> userInspectionPlanEntityQueryWrapper = new QueryWrapper<>() ;
        userInspectionPlanEntityQueryWrapper.eq("is_del",0) ;
        userInspectionPlanEntityQueryWrapper.in("status",statusList) ;
        List<UserInspectionPlanEntity> planList = userInspectionPlanService.list(userInspectionPlanEntityQueryWrapper) ;

        if (!CollectionUtils.isEmpty(planList)){
            List<PlanAgentEntity> planAgentEntityList = planAgentService.listByType(BusiTypeEnum.INSPECTIONORDER.getCode()) ;
            if (CollectionUtils.isEmpty(planAgentEntityList)){
                return;
            }
            //读取巡检计划所有提醒时间
            QueryWrapper<PlanRemindEntity> wrapper = new QueryWrapper<>() ;
            wrapper.eq("is_del",0) ;
            wrapper.eq("type", BusiTypeEnum.INSPECTIONORDER.getCode()) ;
            List<PlanRemindEntity> remindEntityList = planRemindService.list(wrapper) ;

            List<UserInspectionPlanScopeEntity> inspectionPlanScopeEntityList = userInspectionPlanScopeService.list() ;
            planList.stream().forEach(e->{

                if (e.getPlanEndTime().before(new Date())){
                    //结束时间早于当前时间，工单结束。结束+逾期未处理
                    e.setResult(PlanResultEnum.OVERDUE.getCode());
                    e.setStatus(PlanStatusEnum.OVER.getCode());
                    userInspectionPlanService.updateById(e) ;
                }

                if (PlanStatusEnum.NOT_STARTED.getCode().equals(e.getStatus())) {

                    if (e.getPlanStartTime().before(new Date())){
                        //自动改为进行中 TODO 不自动修改为进行中，必须人工激活
                        //e.setStatus(PlanStatusEnum.STARTED.getCode());
                        //userInspectionPlanService.updateById(e) ;
                    }else {
                        List<Long> agentIdList = planAgentEntityList.stream().filter(pa->pa.getPlanId().equals(e.getPlanId())).map(PlanAgentEntity::getAgentId).collect(Collectors.toList());
                        //未开始，检查提醒
                        if (!CollectionUtils.isEmpty(remindEntityList) && !CollectionUtils.isEmpty(agentIdList)) {
                            remindEntityList.stream().filter(p -> p.getPlanId().equals(e.getPlanId())).forEach(pp -> {
                                if (pp != null) {
                                    agentIdList.forEach(ppa->{
                                        Date remindDate = LocalDateUtils.addDateMinutes(e.getPlanStartTime(), -pp.getLeadTime());
                                        long minutes = (remindDate.getTime() / 60000) - (System.currentTimeMillis() / 60000);
                                        if (minutes == 0) {
                                            //TODO 检查时间，是否到提醒时间了，添加队列
                                            /**
                                             * "标题：巡检提醒
                                             * 提醒内容：
                                             * 你有一个巡检任务需要处理
                                             * 巡检范围：XXXXX
                                             * 巡检时间：2021-04-13 9:00-12:00"
                                             */
                                            InspectionPlanRemindMsg msg = new InspectionPlanRemindMsg() ;
                                            msg.setTitle("巡检提醒");
                                            msg.setContent("你有一个巡检任务需要处理");
                                            msg.setScopeIdList(inspectionPlanScopeEntityList.stream().filter(ppp->ppp.getUserInspectionPlanId().equals(e.getId())).map(UserInspectionPlanScopeEntity::getScopeId).collect(Collectors.toList()));
                                            //处理时间
                                            msg.setTimeStr(LocalDateUtils.getQueueTimeStr(e.getPlanStartTime(),e.getPlanEndTime()));
                                            msg.setReceiver(ppa+"");
                                            queueSendMessageService.sendMessage(INSPECTION_ORDER_REMIND ,msg);
                                        }
                                    });
                                }
                            });
                        }
                    }
                }
            });
        }
    }
}
